﻿using QD.Tools;
using QD_Clients.Code.DbContent;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QD_Clients
{
    public partial class SysInsPkg : BaseForm
    {
        private DateTime StartProcessDate = DateTime.Now;//开始处理时间
        public SysInsPkg()
        {
            InitializeComponent();

            this.gridRetainTable.AutoGenerateColumns = false;
            this.gridRetainTable.EditMode = DataGridViewEditMode.EditOnEnter;
        }

        private void btnCreateInsPkg_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            this.btnCreateInsPkg.Enabled = false;
            //创建安装包
            string qfCode = string.Concat(this.cmbQfCode.SelectedValue);
            if (string.IsNullOrEmpty(qfCode))
            {
                PromptHelper.Prompt("请选择软件名称！");
                this.Cursor = Cursors.Default;
                this.btnCreateInsPkg.Enabled = true;
                return;
            }

            //0.检查安装包路径不可为空
            string insPkgPath = this.txtInsPkgPath.Text;
            if (string.IsNullOrEmpty(insPkgPath))
            {
                PromptHelper.Prompt("请输入安装包路径！");
                this.Cursor = Cursors.Default;
                this.btnCreateInsPkg.Enabled = true;
                return;
            }
            //1.提示是否保存好留置表数据
            if (PromptHelper.PromptOkCancel("请确认是否保存好留置表数据，已保存按【确定】按钮，未保存按【取消】按钮。") == DialogResult.Cancel)
            {
                this.Cursor = Cursors.Default;
                this.btnCreateInsPkg.Enabled = true;
                return;
            }
            //2.调用存储过程（Usp_Sys_CreateInstallBackupForApp）创建安装包
            /*
            //Usp_Sys_CreateInstallBackupForApp主要参考内容:
            //配置库:根据配置库创建bak文件,SELECT * FROM QDResources.dbo.Sys_ConfigTable WHERE TableType = 2的表要清除数据
            //业务库:根据业务库创建bak文件,SELECT * FROM QDResources.dbo.QDDataBase_Install_RTable WHERE QfCode = {QfCode}的表要保留数据
            QDDevPlat_V4 db = new QDDevPlat_V4();
            SqlParameter[] parameters = new SqlParameter[] {
                new SqlParameter("@appCode",SqlDbType.VarChar,128),
                new SqlParameter("@backupFilePath",SqlDbType.VarChar,1000),
                new SqlParameter("@successTag",SqlDbType.Bit,1),
                new SqlParameter("@errorMessage",SqlDbType.VarChar,-1),
                new SqlParameter("@masterBackupFileName",SqlDbType.VarChar,1000),
                new SqlParameter("@configBackupFileName",SqlDbType.VarChar,1000)
            };
            parameters[0].Value = qfCode;
            parameters[1].Value = insPkgPath;
            parameters[2].Direction = ParameterDirection.Output;
            parameters[3].Direction = ParameterDirection.Output;
            parameters[4].Direction = ParameterDirection.Output;
            parameters[5].Direction = ParameterDirection.Output;

            DataSet dsDiff = db.RunProcedure("Usp_Sys_CreateInstallBackupForApp", parameters);
            bool successTag = false;
            string errorMessage = "";
            string masterBackupFileName = "";
            string configBackupFileName = "";

            if (parameters != null && parameters.Length >= 6)
            {
                if (parameters[2].Value != null && !string.IsNullOrEmpty(parameters[2].Value.ToString()))
                {
                    successTag = bool.Parse(parameters[2].Value.ToString());
                }
                errorMessage = string.Concat(parameters[3].Value);
                masterBackupFileName = string.Concat(parameters[4].Value);
                configBackupFileName = string.Concat(parameters[5].Value);
            }
            */

            this.cmbQfCode.Enabled = false;
            this.txtInsPkgPath.Enabled = false;
            this.gridRetainTable.Enabled = false;
            this.btnDeleteRow.Enabled = false;
            this.btnSaveRetainData.Enabled = false;
            this.btnCreateInsPkg.Enabled = false;

            //创建进度计时器
            Timer processTimer = new Timer();
            processTimer.Enabled = true;
            processTimer.Interval = 1000;
            processTimer.Tick += new System.EventHandler(this.ProcessTimer_Tick);
            processTimer.Start();

            StartProcessDate = DateTime.Now;
            //this.lblStatus.Visible = true;

            bool successTag = false;
            string errorMessage = "";
            string masterBackupFileName = "";
            string configBackupFileName = "";

            Task task = Task.Run(() =>
            {
                CreateInstallBackupForApp(qfCode, insPkgPath, out successTag, out errorMessage, out masterBackupFileName, out configBackupFileName);
            }).ContinueWith(t =>
            {
                processTimer.Stop();
                processTimer = null;
                this.cmbQfCode.Enabled = true;
                this.txtInsPkgPath.Enabled = true;
                this.gridRetainTable.Enabled = true;
                this.btnDeleteRow.Enabled = true;
                this.btnSaveRetainData.Enabled = true;
                this.btnCreateInsPkg.Enabled = true;

                //3.提示创建安装包结果
                this.cbxSuccessTag.Checked = successTag;
                if (successTag)
                {
                    this.txtMasterBackupFileName.Text = masterBackupFileName;
                    this.txtConfigBackupFileName.Text = configBackupFileName;
                    PromptHelper.Prompt("制作安装包成功！");
                }
                else
                {
                    PromptHelper.Prompt("制作安装包失败！" + errorMessage);
                }

                this.Cursor = Cursors.Default;
                this.btnCreateInsPkg.Enabled = true;

            });
        }

        /// <summary>
        /// 创建安装包
        /// </summary>
        private void CreateInstallBackupForApp(string qfCode,string insPkgPath,out bool successTag,out string errorMessage,out string masterBackupFileName,out string configBackupFileName)
        {
            successTag = false;
            errorMessage = "";
            masterBackupFileName = "";
            configBackupFileName = "";

            QDDevPlat_V4 db = new QDDevPlat_V4();
            SqlParameter[] parameters = new SqlParameter[] {
                new SqlParameter("@appCode",SqlDbType.VarChar,128),
                new SqlParameter("@backupFilePath",SqlDbType.VarChar,1000),
                new SqlParameter("@successTag",SqlDbType.Bit,1),
                new SqlParameter("@errorMessage",SqlDbType.VarChar,-1),
                new SqlParameter("@masterBackupFileName",SqlDbType.VarChar,1000),
                new SqlParameter("@configBackupFileName",SqlDbType.VarChar,1000)
            };
            parameters[0].Value = qfCode;
            parameters[1].Value = insPkgPath;
            parameters[2].Direction = ParameterDirection.Output;
            parameters[3].Direction = ParameterDirection.Output;
            parameters[4].Direction = ParameterDirection.Output;
            parameters[5].Direction = ParameterDirection.Output;

            DataSet dsDiff = db.RunProcedure("Usp_Sys_CreateInstallBackupForApp", parameters);
            

            if (parameters != null && parameters.Length >= 6)
            {
                if (parameters[2].Value != null && !string.IsNullOrEmpty(parameters[2].Value.ToString()))
                {
                    successTag = bool.Parse(parameters[2].Value.ToString());
                }
                errorMessage = string.Concat(parameters[3].Value);
                masterBackupFileName = string.Concat(parameters[4].Value);
                configBackupFileName = string.Concat(parameters[5].Value);
            }
        }

        /// <summary>
        /// 更新运行时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProcessTimer_Tick(object sender, EventArgs e)
        {
            int totalProcessSeconds = Convert.ToInt32(new TimeSpan(DateTime.Now.Ticks).Subtract(new TimeSpan(StartProcessDate.Ticks)).TotalSeconds);
            //转换成相应的大单位            
            int processDays = 0;
            int processHours = 0;
            int processMinutes = 0;
            int processSeconds = 0;

            processDays = Convert.ToInt32(totalProcessSeconds / (24 * 60 * 60));
            processHours = Convert.ToInt32((totalProcessSeconds - processDays * (24 * 60 * 60)) / (60 * 60));
            processMinutes = Convert.ToInt32((totalProcessSeconds - processDays * (24 * 60 * 60) - processHours * (60 * 60)) / (60));
            processSeconds = Convert.ToInt32((totalProcessSeconds - processDays * (24 * 60 * 60) - processHours * (60 * 60) - processMinutes * (60)) / (1));

            string processTimeDesc = "";
            if (processDays > 0)
            {
                processTimeDesc = processDays.ToString() + "天" + processHours.ToString() + "时" + processMinutes.ToString() + "分" + processSeconds.ToString() + "秒";
            }
            else if (processDays == 0 && processHours > 0)
            {
                processTimeDesc = processHours.ToString() + "时" + processMinutes.ToString() + "分" + processSeconds.ToString() + "秒";
            }
            else if (processDays == 0 && processHours == 0 && processMinutes > 0)
            {
                processTimeDesc = processMinutes.ToString() + "分" + processSeconds.ToString() + "秒";
            }
            else
            {
                processTimeDesc = processSeconds.ToString() + "秒";
            }

            this.toolStripStatusLabel1.Text = "已运行" + processTimeDesc;
        }

        private void btnSaveRetainData_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            this.btnSaveRetainData.Enabled = false;

            //保存留置表数据
            string qfCode = string.Concat(this.cmbQfCode.SelectedValue);
            if (string.IsNullOrEmpty(qfCode))
            {
                PromptHelper.Prompt("请选择软件名称！");
                this.Cursor = Cursors.Default;
                this.btnSaveRetainData.Enabled = true;
                return;
            }
            
            if (this.gridRetainTable.DataSource != null)
            {
                DataTable dtRetainTable = (DataTable)this.gridRetainTable.DataSource;
                dtRetainTable.AcceptChanges();
                List<string> updateCommandList = new List<string>();
                StringBuilder updateCommand = new StringBuilder();

                if (dtRetainTable.Rows.Count > 0)
                {                    
                    updateCommand.Append("INSERT INTO QDResources.dbo.QDDataBase_Install_RTable(QfCode,TableCode,TableTitle,RetainCode) VALUES");
                    string tableCode = "";
                    string tableTitle = "";
                    string retainCode = "";

                    for (int i = 0; i < dtRetainTable.Rows.Count; i++)
                    {
                        tableCode = string.Concat(dtRetainTable.Rows[i]["TableCode"]);
                        tableTitle = string.Concat(dtRetainTable.Rows[i]["TableTitle"]);
                        retainCode = string.Concat(dtRetainTable.Rows[i]["RetainCode"]);
                        if (!string.IsNullOrEmpty(tableCode))
                        {
                            updateCommand.Append("('" + qfCode + "','" + tableCode + "','" + tableTitle + "','" + retainCode + "'),");
                        }
                        else
                        {
                            PromptHelper.Prompt("表名不可为空！");
                            this.Cursor = Cursors.Default;
                            this.btnSaveRetainData.Enabled = true;
                            return;
                        }
                    }
                    updateCommand.Remove(updateCommand.Length - 1, 1).Append(";");                    
                }
                //删除(一定要先删除后新增)
                string deleteCommand = "DELETE FROM QDResources.dbo.QDDataBase_Install_RTable WHERE QfCode = '" + qfCode + "';";
                //updateCommandList.Add(deleteCommand);
                //新增
                if (updateCommand.Length > 0)
                {
                    //updateCommandList.Add(updateCommand.ToString());
                    updateCommand.Insert(0,deleteCommand);
                }
                else
                {
                    updateCommand.Append(deleteCommand);
                }

                QDDevPlat_V4 db = new QDDevPlat_V4();
                try
                {
                    db.ExecuteNonQuery(updateCommand.ToString());
                    PromptHelper.Prompt("保存留置表成功！");
                }
                catch(Exception ex)
                {
                    PromptHelper.Prompt("保存留置表失败！" + ex.Message);
                }

                this.Cursor = Cursors.Default;
                this.btnSaveRetainData.Enabled = true;
            }
        }

        private void cmbQfCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            //根据软件代号获取留置表
            DataTable dtApp = (DataTable)this.cmbQfCode.DataSource;
            string qfCode = string.Concat(this.cmbQfCode.SelectedValue);
            if (!string.IsNullOrEmpty(qfCode))
            {
                QDDevPlat_V4 db = new QDDevPlat_V4();
                DataTable dtRetainTable = db.Query("SELECT * FROM QDResources.dbo.QDDataBase_Install_RTable WHERE QfCode = '" + qfCode + "' order by TableCode");
                this.gridRetainTable.DataSource = dtRetainTable;
                //获取配置库FormTable数据
                string configDatabase = dtApp.AsEnumerable().Where(t => t.Field<string>("QfCode") == qfCode).Select(t => t.Field<string>("ConfigDataBase")).FirstOrDefault();
                if (!string.IsNullOrEmpty(configDatabase))
                {
                    DataTable dtAllTable = db.Query("SELECT TableCode,TableName FROM [" + configDatabase + "].dbo.FormTable WHERE FType = 'U' order by TableCode");
                    //添加扩展软件名称栏位
                    DataColumn dcTableNameExt = new DataColumn("TableNameExt", typeof(string));
                    dcTableNameExt.Expression = "TableName + '(' + TableCode + ')'";
                    dtAllTable.Columns.Add(dcTableNameExt);

                    this.gridRetainTable_TableCode.DataSource = dtAllTable;
                    this.gridRetainTable_TableCode.ValueMember = "TableCode";
                    this.gridRetainTable_TableCode.DisplayMember = "TableNameExt";
                }
            }
        }

        private void SysInsPkg_Load(object sender, EventArgs e)
        {
            //获取软件列表
            QDDevPlat_V4 db = new QDDevPlat_V4();
            DataTable dtApp = db.Query("select * from QDDataBase");            
            //添加扩展软件名称栏位
            DataColumn dcQfNameExt = new DataColumn("QfNameExt", typeof(string));
            dcQfNameExt.Expression = "QfName + '(' + QfCode + ')'";
            dtApp.Columns.Add(dcQfNameExt);
            this.cmbQfCode.DataSource = dtApp;
            this.cmbQfCode.ValueMember = "QfCode";
            this.cmbQfCode.DisplayMember = "QfNameExt";
        }

        private void btnAddRow_Click(object sender, EventArgs e)
        {
            //新增行
            if (this.gridRetainTable.DataSource != null)
            {
                DataTable dtRetainTable = (DataTable)this.gridRetainTable.DataSource;
                //将上一行的留置原因作为新增行留置原因的初始值
                DataRow drRetainTable = dtRetainTable.NewRow();
                if (dtRetainTable.Rows.Count > 0)
                {
                    drRetainTable["RetainCode"] = dtRetainTable.Rows[dtRetainTable.Rows.Count - 1]["RetainCode"];
                }
                dtRetainTable.Rows.Add(drRetainTable);
            }
        }

        private void btnDeleteRow_Click(object sender, EventArgs e)
        {
            //删除行
            DataGridViewSelectedRowCollection selectedRows = this.gridRetainTable.SelectedRows;
            if (selectedRows.Count == 0)
            {
                PromptHelper.Prompt("请选择数据行！");
                return;
            }
            for (int i = selectedRows.Count - 1;i >= 0;i--)
            {
                if (!selectedRows[i].IsNewRow)
                {
                    this.gridRetainTable.Rows.Remove(selectedRows[i]);
                }
            }            
        }

        private void gridRetainTable_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //栏位编辑结束
            //将表名作为表标题的初始值
            if (this.gridRetainTable.Columns[e.ColumnIndex].Name == "gridRetainTable_TableCode")
            {
                string tableCode = string.Concat(this.gridRetainTable.Rows[e.RowIndex].Cells["gridRetainTable_TableCode"].Value);
                if (this.gridRetainTable_TableCode.DataSource != null)
                {
                    DataTable dtAllTable = this.gridRetainTable_TableCode.DataSource as DataTable;
                    string tableName = dtAllTable.AsEnumerable().Where(t => t.Field<string>("TableCode") == tableCode).Select(t => t.Field<string>("TableName")).FirstOrDefault();
                    this.gridRetainTable.Rows[e.RowIndex].Cells["gridRetainTable_TableTitle"].Value = tableName;
                }
                    
                //this.gridRetainTable.Rows[e.RowIndex].Cells["gridRetainTable_TableTitle"].Value = this.gridRetainTable.Rows[e.RowIndex].Cells["gridRetainTable_TableCode"].Value;
            }
        }

        private void gridRetainTable_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //添加行号
            var grid = sender as DataGridView;
            var rowIdx = (e.RowIndex + 1).ToString();

            var centerFormat = new StringFormat()
            {
                // right alignment might actually make more sense for numbers
                Alignment = StringAlignment.Center,
                LineAlignment = StringAlignment.Center
            };

            var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
            e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
        }

        private void gridRetainTable_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            if (this.gridRetainTable.DataSource != null)
            {
                DataTable dtRetainTable = (DataTable)this.gridRetainTable.DataSource;
                if (dtRetainTable.Rows.Count > 0)
                {
                    e.Row.Cells["gridRetainTable_RetainCode"].Value = dtRetainTable.Rows[dtRetainTable.Rows.Count - 1]["RetainCode"];
                }
            }
        }

        private void gridRetainTable_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (this.gridRetainTable.Columns[e.ColumnIndex].Name == "gridRetainTable_TableCode")
            {
                string tableCode = string.Concat(this.gridRetainTable.Rows[e.RowIndex].Cells["gridRetainTable_TableCode"].Value);
                if (this.gridRetainTable_TableCode.DataSource != null)
                {
                    DataTable dtAllTable = this.gridRetainTable_TableCode.DataSource as DataTable;
                    string tableName = dtAllTable.AsEnumerable().Where(t => t.Field<string>("TableCode") == tableCode).Select(t => t.Field<string>("TableName")).FirstOrDefault();
                    this.gridRetainTable.Rows[e.RowIndex].Cells["gridRetainTable_TableTitle"].Value = tableName;
                }
                //this.gridRetainTable.Rows[e.RowIndex].Cells["gridRetainTable_TableTitle"].Value = this.gridRetainTable.Rows[e.RowIndex].Cells["gridRetainTable_TableCode"].Value;
            }
        }

        private void gridRetainTable_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            DataGridView grid = (DataGridView)sender;
            int x = grid.CurrentCell.RowIndex;
            int y = grid.CurrentCell.ColumnIndex;

            if (grid.Rows[x].Cells[y] is DataGridViewComboBoxCell && grid.Rows[x].Cells[y].IsInEditMode)
            {
                ComboBox cbo = e.Control as ComboBox;
                if (cbo != null)
                {
                    cbo.DropDownStyle = ComboBoxStyle.DropDown;
                    cbo.AutoCompleteSource = AutoCompleteSource.ListItems;
                    cbo.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                }
            }
        }
    }
}
